package com.mogujie.tt.ui.fragment;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;

import com.mogujie.tt.DB.entity.UserEntity;
import com.mogujie.tt.DB.sp.LoginSp;
import com.mogujie.tt.DB.sp.RegisterSp;
import com.mogujie.tt.R;
import com.mogujie.tt.imservice.event.DetaiLsEvent;
import com.mogujie.tt.imservice.service.IMService;
import com.mogujie.tt.imservice.support.IMServiceConnector;
import com.mogujie.tt.ui.adapter.MypotoGridViewitemAdapter;
import com.mogujie.tt.ui.adapter.MypotoListitemAdapter;
import com.mogujie.tt.ui.base.TTBaseFragment;
import com.mogujie.tt.ui.widget.IMBaseImageView;
import com.mogujie.tt.ui.widget.QuanzMypotoGridDetail;
import com.mogujie.tt.ui.widget.QuanzQzMyPhotoDetail;
import com.mogujie.tt.utils.GETUtil;
import com.mogujie.tt.utils.XListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * Created by Administrator on 2015/11/12.
 */
public class QzMyPhotoAlbumFragment extends TTBaseFragment implements XListView.IXListViewListener {
    private View curView = null;
    private View mHeadViw = null;
    private XListView listview;
    private List<QuanzQzMyPhotoDetail> list;
    private MypotoListitemAdapter adapter;
    private String login_name;
    private String login_password;
    private Handler mHandler;
    private ProgressBar progress_bar;

    private IMServiceConnector imServiceConnector = new IMServiceConnector(){

        @Override
        public void onServiceDisconnected() {}

        @Override
        public void onIMServiceConnected() {

            IMService imService = imServiceConnector.getIMService();
            if (imService == null) {
                return;
            }
            if (!imService.getContactManager().isUserDataReady()) {
                logger.i("detail#contact data are not ready");
            } else {
                init(imService);
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup vg, Bundle bundle) {

        try {
            if (null != curView) {
                ((ViewGroup) curView.getParent()).removeView(curView);
                return curView;
            }
            curView = inflater.inflate(R.layout.quanz_myphotoalbum_fragment, topContentView);
            imServiceConnector.connect(getActivity());
            EventBus.getDefault().register(this);
            listview = (XListView) curView.findViewById(R.id.listView1);
            listview.setPullLoadEnable(false);
            initRes();
            progress_bar = (ProgressBar) curView.findViewById(R.id.progress_bar);
            progress_bar.setVisibility(View.VISIBLE);
            listview.setVisibility(View.GONE);
            list = new ArrayList<QuanzQzMyPhotoDetail>();
            //list.add(getdate1(6));
            getUrlsll();
            adapter=new MypotoListitemAdapter(curView.getContext());
            adapter.setData(list);
            listview.setAdapter(adapter);
            listview.setFocusableInTouchMode(true);
            mHandler = new Handler();
            listview.mHeadG();
            listview.setXListViewListener(this);
            return curView;
        }catch (Exception e){
            System.out.println("1111111QzMyPhotoAlbumFragment   " + e.getMessage());
        }
        return null;
    }
    private void init(IMService imService) {

        if (imService == null) {
            return;
        }
        final UserEntity loginContact = imService.getLoginManager().getLoginInfo();
        if (loginContact == null) {
            return;
        }
        IMBaseImageView portraitImageView = (IMBaseImageView)curView.findViewById(R.id.user_portrait);
        portraitImageView.setDefaultImageRes(R.drawable.tt_default_user_portrait_corner);
        portraitImageView.setCorner(15);
        portraitImageView.setImageResource(R.drawable.tt_default_user_portrait_corner);
        //   portraitImageView.setImageUrl(loginContact.getAvatar());
        portraitImageView.setImageUrl(RegisterSp.instance().getSpDetailedInfo().getDetailedHeadPortrait());
    }

    public void onEventMainThread(DetaiLsEvent event) {
        switch (event){
            case SUCCEED:
                for (int i = 0;i < list.size();i++){
                    for (int j = 0;j < list.get(i).getList().size();j++){
                        if (MypotoGridViewitemAdapter.feed_Id==(list.get(i).getList().get(j).friendId)){
                            list.get(i).getList().remove(j);
                            adapter.notifyDataSetChanged();
                        }
                    }
                }
                break;
        }
    }

    public void onEventMainThread(QuanzMypotoGridDetail event) {
        list.get(0).getList().add(1,event);
        XListD();
        adapter.notifyDataSetChanged();
        //EventBus.getDefault().unregister(this);//卸载注册事件
    }

    public QuanzQzMyPhotoDetail getdate1(int i){
        QuanzQzMyPhotoDetail hotoDetail=new QuanzQzMyPhotoDetail();
        List<QuanzMypotoGridDetail> list=new ArrayList<QuanzMypotoGridDetail>();
        list.add(dd2(0));
        hotoDetail.time0="今天";
        hotoDetail.time1="";
        hotoDetail.list=list;
        return  hotoDetail;
    }

    public QuanzMypotoGridDetail dd2(int i){
        QuanzMypotoGridDetail list=new QuanzMypotoGridDetail();
        list.setGP("1");
        list.setGcontentText("");
        list.setGimages("");
        list.setGphoto("");
        list.setFriendId(0);
        return list;
    }
    private void initRes() {

        mHeadViw = LayoutInflater.from(getActivity()).inflate(R.layout.quanz_qz_head, null);
        listview.addHeaderView(mHeadViw, null, false);
        setTopRightButton(R.drawable.feed_more);
        setTopTitle(getActivity().getString(R.string.page_quanz_qz));
        setTopLeftButton(R.drawable.tt_top_back);
        topLeftContainerLayout.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                getActivity().finish();
            }
        });
        setTopLeftText(getResources().getString(R.string.top_left_back));    }

    @Override
    protected void initHandler() {

    }

    public void getUrlsll() {
        Nmap.clear();
        Npo.clear();
        login_name = LoginSp.instance().getLoginIdentity().getLoginName();
        login_password = LoginSp.instance().getLoginIdentity().getPwd();
        new AsyncTask<String, Void, Object>() {
            protected void onPostExecute(Object result) {
                super.onPostExecute(result);
                System.out.println("777777777777  " + result.toString());
                progress_bar.setVisibility(View.GONE);
                listview.setVisibility(View.VISIBLE);
                analysiss(result.toString());
                XListD();
                adapter.notifyDataSetChanged();
            }
            protected Object doInBackground(String... params) {
                String result = GETUtil.instance().sendGet(GETUtil.instance().getRequestText5("public", "Index", "getUserTimeLine", login_name, login_password, null, String.valueOf(LoginSp.instance().getLoginIdentity().getLoginId())
                        , RegisterSp.instance().getSpDetailedInfo().getDetailedNickName(), "0", "0", "20", "1"));
                return result;
            }
        }.execute();
    }
    private Map<String,String> Nmap = new HashMap<String,String>();
    private Map<String,String> Npo = new HashMap<String,String>();
    private void analysiss(String result){
        try {
            JSONObject array = new JSONObject(result);
            JSONArray data = array.getJSONArray("data");
            if ("[]".equals(data.toString())){
                list.add(getdate1(0));
                return;
            }
            JSONObject obj;
            for (int i=0;i<data.length();i++){
                obj=data.getJSONObject(i);
                data(obj, i);
            }
            data1();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void XListD(){
        if (list.size()>1){
            listview.setPullLoadEnable(true);
            int j=0;
            for (int i = 0; i < list.size();i++){
                j=j+list.get(i).getList().size();
            }
            if (j < 5) {
                listview.mFooter2();
            } else {
                listview.mFooter();
            }
        }else {
            if (list.get(0).getList().size() > 1) {
                listview.setPullLoadEnable(true);
                if (list.get(0).getList().size() < 5) {
                    listview.mFooter2();
                } else {
                    listview.mFooter();
                }
            } else if (list.get(0).getList().size() == 1) {
                listview.mFooter1();
                listview.setPullLoadEnable(true);
            }
        }
    }

    private int bzz=0;
    private void data1() {

        long tm = System.currentTimeMillis();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String time = sdf.format(tm);
        System.out.println("77777778888"+Npo.get(0+"")+"   "+time);
        for (int i=0;i<Npo.size();i++){
            QuanzQzMyPhotoDetail hotoDetail=new QuanzQzMyPhotoDetail();
            List<QuanzMypotoGridDetail> list1=new ArrayList<QuanzMypotoGridDetail>();
            if (Npo.get(i+"").equals(time)||Npo.get(i+"")==time){
                bzz=1;
                System.out.println("77777778888");
                list1.add(dd2(0));
                hotoDetail.time0="今天";
                hotoDetail.time1="";
                String[] Sz = Nmap.get(Npo.get(i+"")).split("TT");

                for (int i1=0;i1<Sz.length;i1++){
                    try {
                        QuanzMypotoGridDetail list11=new QuanzMypotoGridDetail();
                        JSONObject TTim = new JSONObject(Sz[i1]);
                        list11.setGP(TTim.getString("GP"));
                        list11.setGphoto(TTim.getString("Gphoto"));
                        list11.setGimages(TTim.getString("Gimages"));
                        list11.setType(TTim.getString("Type"));
                        list11.setGcontentText(TTim.getString("GcontentText"));
                        list11.setFriendId(Integer.valueOf(TTim.getString("FriendId")));
                        System.out.println("77777755=" + TTim.getString("GcontentText"));
                        list1.add(list11);
                    } catch (Exception e) {
                        System.out.println("1111111Qz  " + e.getMessage());
                    }
                }
                hotoDetail.list=list1;
                list.add(hotoDetail);
            }else {
               if (bzz==0){
                   list.add(getdate1(0));
                   bzz=1;
               }
                String[] Sz = Nmap.get(Npo.get(i+"")).split("TT");

                for (int i1=0;i1<Sz.length;i1++){
                    try {
                        QuanzMypotoGridDetail list11=new QuanzMypotoGridDetail();
                        JSONObject TTim = new JSONObject(Sz[i1]);
                        hotoDetail.time0=TTim.getString("time0");
                        hotoDetail.time1=TTim.getString("time1");
                        list11.setGP(TTim.getString("GP"));
                        list11.setGphoto(TTim.getString("Gphoto"));
                        list11.setGimages(TTim.getString("Gimages"));
                        list11.setType(TTim.getString("Type"));
                        list11.setGcontentText(TTim.getString("GcontentText"));
                        list11.setFriendId(Integer.valueOf(TTim.getString("FriendId")));
                        list1.add(list11);
                    } catch (Exception e) {
                        System.out.println("1111111Qz  " + e.getMessage());
                    }
                }
                hotoDetail.list=list1;
                list.add(hotoDetail);
            }
        }
    }

    private int biao=0;
    private void data(final JSONObject obj,int post) throws JSONException {
        if (obj==null)
            return;
        String ctime=obj.getString("ctime").split(" ")[0];

        if(Nmap.size()>0){
            String m=Nmap.get(ctime);
            if (!"".equals(m)&&m!=null){
                Map<String,Object> productMap=new HashMap<String,Object>();
                productMap.put("time0", ctime.split("-")[2]);
                productMap.put("time1", ctime.split("-")[1]);
                productMap.put("GP","");
                productMap.put("Type",obj.getString("type"));
                if (obj.getString("type").equals("post")){
                    productMap.put("Gphoto","");
                }else if (obj.getString("type").equals("postimage")){
                    if (obj.getString("has_attach").equals("0")){
                        productMap.put("Gphoto","");
                    }else if (obj.getString("has_attach").equals("1")){
                        String attach=obj.getString("attach");
                        productMap.put("Gphoto",attach.toString().replace("\\",""));
                    }
                }else{
                    productMap.put("Gphoto","");
                }
                productMap.put("Gimages","");
                productMap.put("GcontentText",obj.getString("content"));
                productMap.put("FriendId", obj.getString("feed_id"));
                JSONObject jsonObject = new JSONObject(productMap);
                Nmap.put(ctime, m+jsonObject.toString()+"TT");
            }else {
                Map<String,Object> productMap=new HashMap<String,Object>();
                productMap.put("time0", ctime.split("-")[2]);
                productMap.put("time1", ctime.split("-")[1]);
                productMap.put("GP","");
                productMap.put("Type",obj.getString("type"));
                if (obj.getString("type").equals("post")){
                    productMap.put("Gphoto","");
                }else if (obj.getString("type").equals("postimage")){
                    if (obj.getString("has_attach").equals("0")){
                        productMap.put("Gphoto","");
                    }else if (obj.getString("has_attach").equals("1")){
                        String attach=obj.getString("attach");
                        productMap.put("Gphoto",attach.toString().replace("\\",""));
                    }
                }else{
                    productMap.put("Gphoto","");
                }
                productMap.put("Gimages","");
                productMap.put("GcontentText",obj.getString("content"));
                productMap.put("FriendId", obj.getString("feed_id"));
                JSONObject jsonObject = new JSONObject(productMap);
                Nmap.put(ctime, jsonObject.toString()+"TT");
                Npo.put(biao+"",ctime);
                biao++;
            }

        }else {
            Map<String,Object> productMap=new HashMap<String,Object>();
            productMap.put("time0", ctime.split("-")[2]);
            productMap.put("time1", ctime.split("-")[1]);
            productMap.put("GP","");
            productMap.put("Type",obj.getString("type"));
            if (obj.getString("type").equals("post")){
                productMap.put("Gphoto","");
            }else if (obj.getString("type").equals("postimage")){
                if (obj.getString("has_attach").equals("0")){
                    productMap.put("Gphoto","");
                }else if (obj.getString("has_attach").equals("1")){
                    String attach=obj.getString("attach");
                    productMap.put("Gphoto",attach.toString().replace("\\",""));
                }
            }else{
                productMap.put("Gphoto","");
            }
            productMap.put("Gimages","");
            productMap.put("GcontentText",obj.getString("content"));
            productMap.put("FriendId", obj.getString("feed_id"));
            JSONObject jsonObject = new JSONObject(productMap);
            Nmap.put(ctime, jsonObject.toString()+"TT");
            Npo.put(biao+"",ctime);
            biao++;
        }
        System.out.println("77777777ooo"+Nmap);

    }

    private int Upwardmark=2;
    @Override
    public void onRefresh() {
        onLoad();
    }

    @Override
    public void onLoadMore() {

        new AsyncTask<String, Void, Object>() {
            protected void onPostExecute(Object result) {
                super.onPostExecute(result);
                try {
                    JSONObject array = new JSONObject(result.toString());
                    JSONArray data = array.getJSONArray("data");
                    if (data.toString().equals("[]")) {
                        listview.mFootYc();
                    }else{
                        Upwardmark++;
                        analysiss(result.toString());

                        XListD();
                        adapter.notifyDataSetChanged();
                        onLoad();
                    }
                }catch (Exception e) {
                    System.out.println("1111111Qz  " + e.getMessage());
                }
            }
            protected Object doInBackground(String... params) {
                String result = GETUtil.instance().sendGet(GETUtil.instance().getRequestText5("public", "Index", "getUserTimeLine", login_name, login_password, null, String.valueOf(LoginSp.instance().getLoginIdentity().getLoginId())
                        , RegisterSp.instance().getSpDetailedInfo().getDetailedNickName(), "0", "0", "20", String.valueOf(Upwardmark)));
                return result;
            }
        }.execute();
    }

    private void onLoad() {
        listview.stopRefresh();
        listview.stopLoadMore();
    }
}
